package org.example.iol;

import java.io.*;

/**
 * 编码转换
 */
public class Demo02 {
    public static void main(String[] args) throws IOException {
        //读取GDK编码文件
        InputStreamReader isr = new InputStreamReader(new FileInputStream("E:/IDEA-file/newFile.txt"),"GBK");
        //将文件以UTF-8编码导出
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:/IDEA-file/newFileUtf-8.txt"),"UTF-8");
        int i=0;
        while ((i=isr.read())!=-1){
            System.out.println((char)i);
            osw.write(i);
        }
        osw.flush();
        osw.close();
        isr.close();
//        fixEncoding("E:/newFile.txt","E:/newFileUtf-8.txt");
    }

    /**
     * 修复乱码文件，转换文件编码格式
     *
     * @throws UnsupportedEncodingException
     */
    public static void fixEncoding(String target, String newPath) throws IOException {
        //读取GDK编码文件
        InputStreamReader isr = new InputStreamReader(new FileInputStream(target));
        BufferedReader br = new BufferedReader(isr);
        //将文件以UTF-8编码导出
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(newPath), "UTF-8");
        String str2 = null;
//        while ((str2=br.readLine())!=null){
//            //将字符串转为字节数组，并设置原编码格式：GBK
//            byte[] bytes = str2.getBytes("GBK");
//        }

        String str = "绐楀墠鏄庢湀鍏夛紝鐤戞槸鍦颁笂闇溿€�";//GBK
        byte[] bytes = str.getBytes("GBK");
//        System.out.println(new String(bytes));
        String s = new String(bytes);
        //传出文件
        osw.write(s);
        osw.flush();
        osw.close();
    }
}
